<template>
  <div class="order-pay">
    <h2>立即支付</h2>
    <el-card>
      <!-- 订单详情 -->
      <div class="order-info">
        <h3>订单详情</h3>
        <p>商品名称：{{ dish.name }}</p>
        <p>购买数量：{{ order.quantity }}</p>
        <p>配送地址：{{ selectedAddress?.fullAddress }}</p>
        <p>总金额：¥ {{ order.totalPrice.toFixed(2) }}</p>
      </div>

      <!-- 支付方式 -->
      <div class="payment-methods">
        <h3>选择支付方式</h3>
        <el-radio-group v-model="paymentMethod">
          <el-radio label="alipay">支付宝</el-radio>
          <el-radio label="wechat">微信支付</el-radio>
        </el-radio-group>
      </div>

      <!-- 确认支付按钮 -->
      <el-button type="primary" @click="handleConfirmPay">确认支付</el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { apiGet, apiPost } from '@/utils/api';

// 从路由参数中获取订单信息
const router = useRouter();
const order = ref({
  dishId: Number(router.currentRoute.value.query.dishId),
  quantity: Number(router.currentRoute.value.query.quantity),
  addressId: Number(router.currentRoute.value.query.addressId),
  totalPrice: Number(router.currentRoute.value.query.totalPrice),
});

// 商品信息
const dish = ref({
  dishId: order.value.dishId,
  name: '示例菜品',
  price: 50,
});

// 配送地址
const addresses = ref<any[]>([]);
const selectedAddress = computed(() => {
  return addresses.value.find((addr) => addr.id === order.value.addressId);
});

// 支付方式
const paymentMethod = ref('alipay');

// 获取配送地址列表
const fetchAddresses = async () => {
  try {
    const { data } = await apiGet('/user/addresses');
    addresses.value = data;
  } catch (error) {
    ElMessage.error('获取配送地址失败');
    console.error('获取配送地址失败:', error);
  }
};

// 处理确认支付
const handleConfirmPay = async () => {
  try {
    // 调用支付接口
    await apiPost('/order/pay', {
      dishId: order.value.dishId,
      quantity: order.value.quantity,
      addressId: order.value.addressId,
      totalPrice: order.value.totalPrice,
      paymentMethod: paymentMethod.value,
    });

    ElMessage.success('支付成功');
    router.push('/order/success'); // 跳转到支付成功页面
  } catch (error) {
    ElMessage.error('支付失败');
    console.error('支付失败:', error);
  }
};

// 初始化时获取配送地址
onMounted(() => {
  fetchAddresses();
});
</script>

<style scoped>
.order-pay {
  max-width: 600px;
  margin: 20px auto;
}
.order-info {
  margin-bottom: 20px;
}
.payment-methods {
  margin-bottom: 20px;
}
</style>